<?php

class access_ctrl extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    //获取WXcfg
    public function get_cfg()
    {
        if (!$this->ajax_err) {

            $url = urldecode($_REQUEST["url"]);

            $jsapiTicket = ccLoad('jsapiTicket');
            if($jsapiTicket != false){
                $jsapiTicket = ccLoad('jsapiTicket');
            }else{
                $jsapiTicket = $this->getJsApiTicket()->ticket;
                ccSave('jsapiTicket',$jsapiTicket,7200);
            }

            // 注意 URL 一定要动态获取，不能 hardcode.
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            //dump($protocol.'----'.$_SERVER[HTTP_HOST].'----'.$_SERVER[REQUEST_URI].'----'.$_SERVER['QUERY_STRING']);
            //$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            //$url = 'https://'.$_SERVER['HTTP_HOST'].'/hwgame/?'.$_SERVER['QUERY_STRING'];
            //dump($url);
            $timestamp = time();
            $nonceStr = $this->createNonceStr();

            // 这里参数的顺序要按照 key 值 ASCII 码升序排序
            $string = "jsapi_ticket=".$jsapiTicket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;

            $signature = sha1($string);

            $signPackage = array(
                "appId"     => APP_ID,
                "nonceStr"  => $nonceStr,
                "timestamp" => $timestamp,
                "url"       => $url,
                "signature" => $signature,
                "rawString" => $string,
            );

            $this->ajax($signPackage);
        } else {
            return $this->ajax('', array(1, '未登录', 1, '请登录'));
        }
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $url = API_IP.'hwcrmweb/wechat/getJsTicket.do';
        $res = json_decode($this->httpGet($url));

        return $res;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }


}